<?php
declare (strict_types=1);

namespace app\business\controller;

use app\common\model\BusinessCensus;
use app\common\model\BusinessRole;
use app\common\model\Menu;
use app\common\model\UserNotify;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;

class Index extends Base
{
    protected $sort = [];

    /**
     * 显示资源列表
     *
     * @return string
     */
    public function index()
    {
        $rules = '';
        if ($this->admin['role_id'] != 1) {
            $rules = (new BusinessRole())->where('id', $this->admin['role_id'])->value('rules');
        }
        $menus = (new Menu())->getMenu($rules, 1, 2);

        View::assign('menus', $menus);
        View::assign('noticeCount', UserNotify::where('admin_part', 1)
            ->whereNotLike('admin_read_ids', '%' . $this->admin->id . '%')->count());
        return View::fetch();
    }

    public function welcome()
    {
        $result = BusinessCensus::getCommonCensus($this->business, $this->request->get('data'));
        $list = \app\common\model\Order::where(['business_id' => $this->business->id, 'is_del' => 0, 'status' => 2])
            ->field('id,sn')->order('pay_time', 'desc')->limit(5)
            ->with('products')
            ->select();
        foreach ($list as &$v) {
            $products = $v->products()->field('pid,title,icon,num')->select()->toArray();
            foreach ($products as $item) {
                $v->product .= $item['title'] . ' ' . '数量：' . $item['num'] . ' / ';
                $v->icon = $item['icon'];
            }

        }
        View::assign('list', $list);
        View::assign('result', $result);
        return View::fetch();
    }

    public function getDiagramCensus()
    {
        $date = $this->request->get('date', date('Y-m'));
        $result = BusinessCensus::getCommonCensus($this->business, ['month'=>$date]);
        $diagramDate = [];
        $diagramValue = [];
        foreach ($result['diagramCensus'] as $item) {
            $diagramDate[] = $item['month'] . '-' . $item['day'];
            $diagramValue[] = $item['value'];
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => ['diagramDate' => $diagramDate, 'diagramValue' => $diagramValue]]);
    }

    public function clear_cache()
    {
        return Cache::clear() ? json(['code' => 1, 'msg' => '已清除']) : json(['code' => -1, 'msg' => '加载失败']);
    }
}
